#!/usr/bin/python
#
# Copyright (C) Nicola Bizzoca   2006/2007  <hannibal_smith@users.sourceforge.net>
# Copyright (C) Simone Economo   2006/2007  <ekoes@users.sourceforge.net>
# 
#	This file is part of Absynth-FTP.
#
#	Absynth-FTP is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 3 of the License, or
#	(at your option) any later version.
#
#	Absynth-FTP is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os, sys

try:
	import gtk, gtk.glade, gobject
except ImportError:
	print >> sys.stderr, "Absynth needs GTK 2.10 or above to run."
	sys.exit(1)
	
from lib.GNOMEConf import GtkConfig
import conf as Config
import abcommon as Utils

from twisted.internet import gtk2reactor
gtk2reactor.install()
from twisted.internet import reactor
from lib.libftp2 import *

conf = GtkConfig()

class XMLtree:
	_instance = None
	
	def __init__(self, widget = False):
		gladeFile = Config.GLADE_MAIN_WINDOW
		self.methods = (widget and gtk.glade.XML(gladeFile, widget)) \
					 or gtk.glade.XML(gladeFile)
					 
		self.connectSignals = self.methods.signal_autoconnect
		self.getWidget = self.methods.get_widget

class Widgets:
	
	__list__ = {
		# Name 		 : Load at startup?
		"LocalView"	 : True,
		"RemoteView" : False,
		"AboutDialog": False,
		"SysTray"	 : True,
		"LogView"	 : True,
		"MainWindow" : True,
		"RemoteNotebook" : True,
		"WelcomeTab" : True,
		"DownloadView": True,
		"UploadView"  : True,
	}
	
	@staticmethod
	def selectWidget(name):
		try:
			Widgets.__list__[name]
			return sys.modules["widgetsGtk.%s" % name]
		except:
			return None
	
	@staticmethod
	def getList():
		return Widgets.__list__
	
	def __init__(self):
		self.gladeTree = XMLtree
	 	self.XMLtree = Utils.Invoker(self.gladeTree)
	 	
	def changeXMLtree(self, root):
		self.XMLtree = self.gladeTree(root)
		
	def connectEvents(self, events):
		for type,callback in events.items():
			self.window.connect(type, callback)
		
class Absynth(Widgets):
	FTPSession = []
	widgetSession = {}
	def __init__(self):
		Widgets.__init__(self)
		for widget in Widgets.getList():
			if Widgets.getList()[widget] is False:
				continue
			else:
				self.widgetSession[widget] = Widgets.selectWidget(widget).UI()
		self.__setUp()
		self.connectEvents()
		
		self.__mainLoop()	

	@staticmethod
	def __mainLoop():
		reactor.run()
	
	def __setUp(self):
		self.log = self.widgetSession["LogView"]
		if conf.get("welcomeTab") == True:
			self.widgetSession["RemoteNotebook"].newTab(None, 
													    [self.widgetSession["WelcomeTab"].tabLabel,
													  	 self.widgetSession["WelcomeTab"].widget])
	
	def connectEvents(self):
		self.XMLtree.connectSignals({
			"on_about" 					 : self.widgetSession["MainWindow"]._loadAboutDialog, 
			"on_ConnectionButton_clicked": self.getFTPConnection,
			"on_AbsynthMain_destroy"	 : self._quitMessage,
			"on_toolbuttonDisconnect_clicked" : self.quitCurrentFTPSession,
		})
		
 	def getFTPConnection(self, *args):
 		self.ftp = FTPClass()
 		self.ftp.setLogger(self.log)
 		self.ftp.connect('connected', self.checkConnect)
 		self.__connectionData = self.widgetSession["MainWindow"].getFTPConnectionData()
 		self.ftp.connectTo(
			self.__connectionData["hostname"],
			self.__connectionData["username"],
			self.__connectionData["password"])

  	def checkConnect(self, id, data):
  		if data == "ok":
  		 self.connectionMade()
		else:
		  self.log.write(data)
		  
	def connectionMade(self):
		remoteView = Widgets.selectWidget("RemoteView").UI(self.ftp, self.log)
		self.widgetSession["RemoteNotebook"].newTab(None, [remoteView.pageLabel, remoteView.pageWidget])
		currentPage = self.widgetSession["RemoteNotebook"].widget.getCurrentPage()
		self.widgetSession["RemoteNotebook"].widget.setPage(currentPage)
		data = {'ftp' : self.ftp,
				'pagewidget' : remoteView.pageWidget,
				'name' : self.__connectionData["hostname"],
				 }
		self.FTPSession.append(data)
		self.widgetSession["DownloadView"].append_session(data)
		self.widgetSession["UploadView"].append_session(data)
		self.log.write("Connesso a ftp://%s@%s con password %s" % (
		self.__connectionData["hostname"],
		self.__connectionData["username"],
		self.__connectionData["password"]))

	def _quitMessage(self, *args):
 		print "Goodbye, my darling Clementine!"
 		print self.FTPSession
 		for session in self.FTPSession:
 			print session
 			session['ftp'].quit()
 			page = self.widgetSession["RemoteNotebook"].widget.getPageFromWidget(session["pagewidget"])
 			self.widgetSession["RemoteNotebook"].widget.removePage(page)
 		reactor.stop()
 		
 	def quitCurrentFTPSession(self, *args):
 		currentPage = self.widgetSession["RemoteNotebook"].widget.getCurrentPage()
 		pageWidget = self.widgetSession["RemoteNotebook"].widget.getWidgetFromPage(currentPage)
 		for session in self.FTPSession:
 			if session["pagewidget"] == pageWidget:
 				session["ftp"].quit()
 				self.widgetSession["RemoteNotebook"].widget.removePage(currentPage)
 				id = self.FTPSession.index(session)
 				del self.FTPSession[id]
 				break